package com.bestcem.xm.component.security.context;

import cn.hutool.core.convert.Convert;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.bestcem.xm.component.security.constant.SecurityConstants;
import com.bestcem.xm.component.security.dto.TokenDTO;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SecurityContextHolder {
    private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>();

    public static void set(String key, Object value) {
        Map<String, Object> map = getLocalMap();
        map.put(key, value == null ? StringUtils.EMPTY : value);
    }

    public static String get(String key) {
        Map<String, Object> map = getLocalMap();
        return Convert.toStr(map.getOrDefault(key, StringUtils.EMPTY));
    }

    public static <T> T get(String key, Class<T> clazz) {
        Map<String, Object> map = getLocalMap();
        //return (T) map.getOrDefault(key, null);
        return Convert.convert(clazz, map.getOrDefault(key, null), null);
    }

    public static Map<String, Object> getLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }

    public static void setUserId(String userId) {
        set(SecurityConstants.USER_ID, userId);
    }

    public static String getUserId() {
        return get(SecurityConstants.USER_ID);
    }

    public static void setOrgId(String orgId) {
        set(SecurityConstants.ORG_ID, orgId);
    }

    public static String getOrgId() {
        return get(SecurityConstants.ORG_ID);
    }

    public static void setToken(TokenDTO token) {
        set(SecurityConstants.TOKEN, token);
    }

    public static TokenDTO getToken() {
        return get(SecurityConstants.TOKEN, TokenDTO.class);
    }

    public static void setOrgCode(String orgCode) {
        set(SecurityConstants.ORG_CODE, orgCode);
    }

    public static String getOrgCode() {
        return get(SecurityConstants.ORG_CODE);
    }
}
